package com.cisetech.web.util;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cisetech.util.Global;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

public class JDBCUtil {
	//需要执行的sql
	//根据id获取数据
	static String getbyIdsql = "SELECT * FROM l_resources WHERE id=";
	//收集查询结果
	public List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();


	public Connection getConn() {
	    String driver = Global.getConfig("JDBC.driver");//"com.mysql.jdbc.Driver";
	    String url = Global.getConfig("JDBC.url");//"jdbc:mysql://localhost:3306/samp_db";
	    String username = Global.getConfig("JDBC.username");//"root";
	    String password = Global.getConfig("JDBC.password");//"";
	    Connection conn = null;
	    try {
	        Class.forName(driver); //classLoader,加载对应驱动
	        conn = (Connection) DriverManager.getConnection(url, username, password);
	    } catch (ClassNotFoundException e) {
	        e.printStackTrace();
	    } catch (SQLException e) {
	        e.printStackTrace();
	    }
	    return conn;
	}
	/**
	 * 查询实例
	 * @return
	 */
	public List<Map<String, Object>> getAll(String id,String sql) {
	    Connection conn = getConn();
	    //String sql = "SELECT * FROM l_resources WHERE id="+id;
	    PreparedStatement pstmt;
	    try {
	        pstmt = (PreparedStatement)conn.prepareStatement(sql);
	        ResultSet rs = pstmt.executeQuery();
	        int col = rs.getMetaData().getColumnCount();
	        while (rs.next()) {
	        	Map<String,Object> rowData = new HashMap<String,Object>();
				for (int i = 1; i <= col; i++) {
					rowData.put(rs.getMetaData().getColumnName(i), rs.getObject(i));
				}
				list.add(rowData);
	        }
	    } catch (SQLException e) {
	        e.printStackTrace();
	    }
	    return list;
	}
	/**
     * 根据id和状态返回想要的数据
     * @param id
     * @param type
     * @return
     */
    public static String getbyId(String id,String type,String e){
    	JDBCUtil jdbc = new JDBCUtil();
		List<Map<String, Object>> list = jdbc.getAll(id,getbyIdsql+id);
		if(list.size()>0){
			if ("url".equals(type)){
				return list.get(0).get("site")==null ? "javascript:void(0)":(String)(list.get(0).get("site"));
			}
			if ("name".equals(type)){
				if ("e".equals(e)){
					return list.get(0).get("e_name")==null ? "无":(String)(list.get(0).get("e_name"));
				}else{
					return list.get(0).get("name")==null ? "无":(String)(list.get(0).get("name"));
				}
			}
		}
		return type;
	}
}
